/*
* Copyright (C) 2008-2009 J-P Nurmi jpnurmi@gmail.com
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License along
* with this program; if not, write to the Free Software Foundation, Inc.,
* 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
*
* $Id: connection.cpp 353 2009-04-27 20:23:58Z jpnurmi $
*/

#include "connection.h"
#include <QStringList>
#include <QSettings>

Connection::Connection() :
    name(),
    host(),
    port(6667),
    nick(),
    pass(),
    autoConnect(false),
    secure(false)
{
    qRegisterMetaTypeStreamOperators<Connection>("Connection");
}

Connection::operator QVariant() const
{
    return QVariant::fromValue(*this);
}

bool Connection::operator==(const Connection& other)
{
    return name == other.name;
}

Connection Connection::load(int index)
{
    QSettings settings;
    settings.beginGroup("Connections");
    return settings.value(QString::number(index)).value<Connection>();
}

void Connection::save(const Connection& connection, int index)
{
    if (index < 0)
        index = connections().indexOf(connection);
    Q_ASSERT(index >= 0);

    QSettings settings;
    settings.beginGroup("Connections");
    settings.setValue(QString::number(index), connection);
}

void Connection::remove(const Connection& connection)
{
    QList<Connection> conns = connections();
    conns.removeAll(connection);

    QSettings settings;
    settings.beginGroup("Connections");
    settings.clear();

    for (int i = 0; i < conns.count(); ++i)
        settings.setValue(QString::number(i), conns.at(i));
}

QList<Connection> Connection::connections()
{
    QSettings settings;
    settings.beginGroup("Connections");
    QStringList keys = settings.childKeys();

    QList<Connection> conns;
    // TODO: is qSort(keys) needed?
    for (int i = 0; i < keys.count(); ++i)
    {
        Q_ASSERT(i == keys.at(i).toInt());
        conns += settings.value(keys.at(i)).value<Connection>();
    }
    return conns;
}
